package views;

import com.toedter.calendar.JCalendar;
import entities.Clientes;
import entities.Feriados;
import entities.Logs;
import entities.Usuarios;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.Beans;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.persistence.Query;
import javax.persistence.RollbackException;
import javax.swing.*;
import logica.ExcelJTableExporter;
import renders.TipoFeriadoRender;

/**
 *
 * @author Facu
 */
public class AltaFeriados extends JPanel {

    public static JFrame frame;
    private Feriados fer;
    private Logs logs;
    private int click;
    private Date dia;
    private JCalendar date;
    private JFrame frame1;
    private JTextArea textArea;
    private JScrollPane scrollPane;
    boolean editando = false;
    int indiceFeriadoNacional = 0;
    int indiceFeriadoProvincial = 1;
    int indiceFeriadoMunicipal = 2;
    private Usuarios usuario;

    public AltaFeriados(Usuarios usuario) {
        this.click = 0;
        this.dia = null;
        textArea = new JTextArea(5, 20);
        initComponents();
        //TODO Falta organizar bien la pantalla de AYUDA
        textArea.setText("Para dar de alta un feriado\n"
                + "1) Escribir la fecha en formato 'D/M/AAAA' y \n"
                + "presionar 'Enter'\n"
                + "o hacer click en el botón 'Agregar feriado' o;\n"
                + "2) Hacer click en el botón ubicado a la derecha \n"
                + "del cuadro de texto y elegir del calendario\n"
                + "el dia correspondiente y luego presionar 'Enter'\n"
                + "o hacer click en el botón 'Agregar feriado' o;\n"
                + "Para eliminar un feriado de la lista tiene que\n"
                + "hacer click en el día que desea borrar y presionar\n"
                + "Supr/Delete en su teclado\n"
                + "\nGracias por utilizar este programa...");
        this.scrollPane = new JScrollPane(textArea);
        if (!Beans.isDesignTime()) {
            entityManager.getTransaction().begin();
        }
        fechaFeriadoDateChooser.setDateFormatString("d/M/yyyy");
        this.usuario = usuario;
        focusFechaActual();
    }

    public JFrame getFrame() {
        return frame;
    }

    private Integer getIDFeriado(Date fecha) {
        Query queryIDFeriado;
        Feriados fer;
        queryIDFeriado = entityManager.createNamedQuery("Feriados.findByFecha");
        queryIDFeriado.setParameter("fecha", fecha);
        fer = (Feriados) queryIDFeriado.getSingleResult();
        return fer.getIdferiados();
    }

    public void setFrame(JFrame frame) {
        AltaFeriados.frame = frame;
    }

    public void setFocus() {
        int row = 0;
        //Hacer focus en el textField del DateChooser al empezar para poder escribir
        fechaFeriadoDateChooser.getDateEditor().getUiComponent().requestFocus();
        Calendar cal = Calendar.getInstance();
        for (Feriados feriados : list) {
            if (feriados.getFecha().before(cal.getTime())) {
                break;
            }
            row++;
        }
        masterTable.scrollRectToVisible(masterTable.getCellRect(row, 0, true));
    }

    public JScrollPane getjScrollPane1() {
        return jScrollPane1;
    }

    public void setjScrollPane1(JScrollPane jScrollPane1) {
        this.jScrollPane1 = jScrollPane1;
    }

    public JTextArea getTextArea() {
        return textArea;
    }

    public void setTextArea(JTextArea textArea) {
        this.textArea = textArea;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("SIAATPU").createEntityManager();
        query = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT f FROM Feriados f ORDER BY f.fecha DESC");
        list = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query.getResultList());
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jButton1 = new javax.swing.JButton();
        SIAATPUEntityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("SIAATPU").createEntityManager();
        feriadosQuery = java.beans.Beans.isDesignTime() ? null : SIAATPUEntityManager.createQuery("SELECT f FROM Feriados f");
        feriadosList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : feriadosQuery.getResultList();
        masterScrollPane = new javax.swing.JScrollPane();
        masterTable = new javax.swing.JTable();
        guardarButton = new javax.swing.JButton();
        fechaFeriadoLabel = new javax.swing.JLabel();
        fechaFeriadoDateChooser = new com.toedter.calendar.JDateChooser();
        tipoFeriadoComboBox = new javax.swing.JComboBox();
        jScrollPane2 = new javax.swing.JScrollPane();
        descripcionTextArea = new javax.swing.JTextArea();
        tipoFeriadoLabel = new javax.swing.JLabel();
        descripcionLabel = new javax.swing.JLabel();
        cancelarButton = new javax.swing.JButton();
        nuevoButton = new javax.swing.JButton();
        borrarButton = new javax.swing.JButton();
        ayudaLabel1 = new javax.swing.JLabel();
        exportarExcelButton = new javax.swing.JButton();

        FormListener formListener = new FormListener();

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jButton1.setText("jButton1");

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, list, masterTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${fecha}"));
        columnBinding.setColumnName("Fecha");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${tipoFeriado}"));
        columnBinding.setColumnName("Tipo Feriado");
        columnBinding.setColumnClass(Character.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${descripcion}"));
        columnBinding.setColumnName("Descripcion");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        masterTable.addMouseListener(formListener);
        masterScrollPane.setViewportView(masterTable);
        masterTable.getColumnModel().getColumn(1).setPreferredWidth(10);
        masterTable.getColumnModel().getColumn(1).setCellRenderer(new TipoFeriadoRender());

        guardarButton.setBackground(new java.awt.Color(1, 154, 210));
        guardarButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        guardarButton.setForeground(new java.awt.Color(255, 255, 255));
        guardarButton.setText("Guardar");
        guardarButton.setEnabled(false);
        guardarButton.addActionListener(formListener);

        fechaFeriadoLabel.setText("Fecha Feriado");

        fechaFeriadoDateChooser.setDateFormatString("d/M/yyyy");
        fechaFeriadoDateChooser.setEnabled(false);

        tipoFeriadoComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Nacional", "Provincial", "Municipal" }));
        tipoFeriadoComboBox.setSelectedIndex(-1);
        tipoFeriadoComboBox.setEnabled(false);

        descripcionTextArea.setColumns(20);
        descripcionTextArea.setRows(5);
        descripcionTextArea.setEnabled(false);
        jScrollPane2.setViewportView(descripcionTextArea);

        tipoFeriadoLabel.setText("Tipo de Feriado:");

        descripcionLabel.setText("Descripción:");

        cancelarButton.setBackground(new java.awt.Color(1, 154, 210));
        cancelarButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        cancelarButton.setForeground(new java.awt.Color(255, 255, 255));
        cancelarButton.setText("Cancelar");
        cancelarButton.setEnabled(false);
        cancelarButton.addActionListener(formListener);

        nuevoButton.setBackground(new java.awt.Color(1, 154, 210));
        nuevoButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        nuevoButton.setForeground(new java.awt.Color(255, 255, 255));
        nuevoButton.setText("Nuevo");
        nuevoButton.addActionListener(formListener);

        borrarButton.setBackground(new java.awt.Color(1, 154, 210));
        borrarButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        borrarButton.setForeground(new java.awt.Color(255, 255, 255));
        borrarButton.setText("Borrar");
        borrarButton.setEnabled(false);
        borrarButton.addActionListener(formListener);

        ayudaLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/help.png"))); // NOI18N
        ayudaLabel1.addMouseListener(formListener);

        exportarExcelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/xls.png"))); // NOI18N
        exportarExcelButton.setText("Exportar");
        exportarExcelButton.addActionListener(formListener);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(masterScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 560, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(tipoFeriadoLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(tipoFeriadoComboBox, javax.swing.GroupLayout.Alignment.TRAILING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(fechaFeriadoDateChooser, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                            .addComponent(fechaFeriadoLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 222, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                                .addComponent(nuevoButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                .addComponent(borrarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                        .addGap(0, 0, Short.MAX_VALUE)))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jScrollPane2)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(cancelarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(guardarButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(descripcionLabel)
                                        .addGap(0, 0, Short.MAX_VALUE))))))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(ayudaLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(exportarExcelButton)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(masterScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 214, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(descripcionLabel)
                            .addComponent(fechaFeriadoLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(fechaFeriadoDateChooser, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(tipoFeriadoLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(tipoFeriadoComboBox))
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 118, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(borrarButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 32, Short.MAX_VALUE)
                            .addComponent(guardarButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(cancelarButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(nuevoButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(ayudaLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(exportarExcelButton)))
                .addGap(1, 1, 1))
        );

        bindingGroup.bind();
    }

    // Code for dispatching events from components to event handlers.

    private class FormListener implements java.awt.event.ActionListener, java.awt.event.MouseListener {
        FormListener() {}
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            if (evt.getSource() == guardarButton) {
                AltaFeriados.this.guardarButtonActionPerformed(evt);
            }
            else if (evt.getSource() == cancelarButton) {
                AltaFeriados.this.cancelarButtonActionPerformed(evt);
            }
            else if (evt.getSource() == nuevoButton) {
                AltaFeriados.this.nuevoButtonActionPerformed(evt);
            }
            else if (evt.getSource() == borrarButton) {
                AltaFeriados.this.borrarButtonActionPerformed(evt);
            }
            else if (evt.getSource() == exportarExcelButton) {
                AltaFeriados.this.exportarExcelButtonActionPerformed(evt);
            }
        }

        public void mouseClicked(java.awt.event.MouseEvent evt) {
            if (evt.getSource() == masterTable) {
                AltaFeriados.this.masterTableMouseClicked(evt);
            }
        }

        public void mouseEntered(java.awt.event.MouseEvent evt) {
            if (evt.getSource() == ayudaLabel1) {
                AltaFeriados.this.ayudaLabel1MouseEntered(evt);
            }
        }

        public void mouseExited(java.awt.event.MouseEvent evt) {
        }

        public void mousePressed(java.awt.event.MouseEvent evt) {
        }

        public void mouseReleased(java.awt.event.MouseEvent evt) {
        }
    }// </editor-fold>//GEN-END:initComponents
    public void focusFechaActual() {

        //Guardo la fecha actual 
        Date fechaActualtest = new Date();
        //Recorro para buscar la fecha mas cercana a la fecha actual       
        int filaFechaCercana = 0;
        for (Feriados feriado : list) {
            //Si la fecha es mayor, voy guardando los numero de las filas
            if (feriado.getFecha().compareTo(fechaActualtest) > 0) {

                filaFechaCercana++;
            }
            //Si la fecha es menor o igual a la actual, me muevo a la ultima fecha mayor cercana a  la actual
            if (feriado.getFecha().compareTo(fechaActualtest) <= 0) {
                masterTable.scrollRectToVisible(masterTable.getCellRect(filaFechaCercana, 0, true));

            }

        }

    }

    private void resetAyudaView() {
        if (this.frame1 == null) {
            this.frame1 = new JFrame("Ayuda");
            this.frame1.setMinimumSize(new Dimension(330, 250));
            this.frame1.setVisible(true);
            this.textArea.setVisible(true);
            this.scrollPane.setVisible(true);
            textArea.setEditable(false);
            this.frame1.setContentPane(scrollPane);
            this.frame1.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        } else {
            this.frame1.setMinimumSize(new Dimension(320, 240));
            this.frame1.setVisible(true);
            this.textArea.setVisible(true);
            this.scrollPane.setVisible(true);
            textArea.setEditable(false);
            this.frame1.setContentPane(scrollPane);
            this.frame1.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        }
    }

    private boolean existeFeriado() {
        int cont = 0;
        int fila = 0;
        Date fechaFeriado = fechaFeriadoDateChooser.getDate();
        for (Feriados feriado : list) {
            if (masterTable.getSelectedRow() == fila) {
            } else {
                if (feriado.getFecha().equals(fechaFeriado)) {
                    cont++;
                }
            }
            fila++;
        }

        if (cont < 1) {
            return false;
        }
        return true;
    }
    private void guardarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guardarButtonActionPerformed
        Date fechaFeriado = fechaFeriadoDateChooser.getDate();
        if ((fechaFeriado == null) || (tipoFeriadoComboBox.getSelectedIndex() == -1)) {
            JOptionPane.showMessageDialog(this, "El campo Fecha Feriado o Tipo Feriado no pueden quedar nulos", "Atención", JOptionPane.ERROR_MESSAGE, null);
        } else if (existeFeriado()) {
            JOptionPane.showMessageDialog(this, "Ya existe el feriado que desea ingresar, "
                    + "FECHA Duplicada", "Atención", WIDTH, null);
            fechaFeriadoDateChooser.requestFocus();
        } else {
            try {
                logs = new Logs();
                logs.setUsuario(usuario);
                fer.setFecha(fechaFeriado);
                fer.setTipoFeriado(((String) tipoFeriadoComboBox.getSelectedItem()).charAt(0));
                fer.setDescripcion(descripcionTextArea.getText());
                if (editando) {
                    entityManager.merge(fer);
                }
                if (fer.getIdferiados() == null) {
                    entityManager.getTransaction().commit();
                    entityManager.getTransaction().begin();
                    Integer idFeriado = getIDFeriado(fer.getFecha());
                    logs.setearObservaciones("Alta", "Feriados", idFeriado, "AltaFeriados");
                } else {
                    logs.setearObservaciones("Modificación", "Feriados", fer.getIdferiados(), "AltaFeriados");
                }
                entityManager.persist(logs);
                entityManager.getTransaction().commit();
                entityManager.getTransaction().begin();

            } catch (RollbackException rex) {
                entityManager.getTransaction().begin();
                List<entities.Feriados> merged = new ArrayList<entities.Feriados>(list.size());
                for (entities.Feriados feriado : list) {
                    merged.add(entityManager.merge(feriado));
                }
                list.clear();
                list.addAll(merged);
            }
            habilitarBotones(false);
            refrescar();
        }

    }//GEN-LAST:event_guardarButtonActionPerformed

    private int indiceTipoFeriadoComboBox() {
        switch ((char) masterTable.getValueAt(masterTable.getSelectedRow(), 1)) {
            case 'N':
                return indiceFeriadoNacional;
            case 'M':
                return indiceFeriadoMunicipal;
            case 'P':
                return indiceFeriadoProvincial;
            default:
                return -1;
        }
    }

    private void masterTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_masterTableMouseClicked
        habilitarBotones(true);
        traerDatosFeriado();
        editando = true;
    }//GEN-LAST:event_masterTableMouseClicked

    private void traerDatosFeriado() {
        fechaFeriadoDateChooser.setDate((Date) masterTable.getValueAt(masterTable.getSelectedRow(), 0));
        tipoFeriadoComboBox.setSelectedIndex(indiceTipoFeriadoComboBox());
        descripcionTextArea.setText((String) masterTable.getValueAt(masterTable.getSelectedRow(), 2));
        fer = list.get(masterTable.getSelectedRow());
    }

    private void cancelarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarButtonActionPerformed
        refrescar();
    }//GEN-LAST:event_cancelarButtonActionPerformed

    private void refrescar() {
        entityManager.getTransaction().rollback();
        entityManager.getTransaction().begin();
        java.util.Collection data = query.getResultList();
        for (Object entity : data) {
            entityManager.refresh(entity);
        }
        list.clear();
        list.addAll(data);
        habilitarBotones(false);
        limpiarBotones();
        editando = false;
    }

    private void limpiarBotones() {
        fechaFeriadoDateChooser.setDate(null);
        tipoFeriadoComboBox.setSelectedIndex(-1);
        descripcionTextArea.setText("");
    }

    private void habilitarBotones(boolean estado) {
        masterTable.setEnabled(!estado);
        fechaFeriadoDateChooser.setEnabled(estado);
        tipoFeriadoComboBox.setEnabled(estado);
        descripcionTextArea.setEnabled(estado);
        nuevoButton.setEnabled(!estado);
        guardarButton.setEnabled(estado);
        cancelarButton.setEnabled(estado);
        borrarButton.setEnabled(estado);
    }

    private void nuevoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nuevoButtonActionPerformed
        fer = new entities.Feriados();
        logs = new Logs();
        logs.setUsuario(usuario);
        entityManager.persist(fer);
        list.add(fer);
        int row = list.size() - 1;
        masterTable.setRowSelectionInterval(row, row);
        masterTable.scrollRectToVisible(masterTable.getCellRect(row, 0, true));
        habilitarBotones(true);
        editando = false;
        borrarButton.setEnabled(false);
    }//GEN-LAST:event_nuevoButtonActionPerformed

    private void borrarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_borrarButtonActionPerformed
        int respuesta = JOptionPane.showConfirmDialog(frame, "Desea confirmar el borrado de feriado/s?", "Borrado de feriado", JOptionPane.YES_NO_OPTION);
        if (respuesta == JOptionPane.YES_OPTION) {
            int[] selected = masterTable.getSelectedRows();
            List<entities.Feriados> toRemove = new ArrayList<entities.Feriados>(selected.length);
            for (int idx = 0; idx < selected.length; idx++) {
                entities.Feriados fer = list.get(masterTable.convertRowIndexToModel(selected[idx]));
                toRemove.add(fer);
                logs = new Logs();
                logs.setUsuario(usuario);
                logs.setearObservaciones("Borrado", "Feriados", fer.getIdferiados(), "AltaFeriados");
                entityManager.persist(logs);
                entityManager.remove(fer);
            }
            list.removeAll(toRemove);
            entityManager.getTransaction().commit();
            entityManager.getTransaction().begin();
            habilitarBotones(false);
            limpiarBotones();
        }
    }//GEN-LAST:event_borrarButtonActionPerformed

    private void ayudaLabel1MouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ayudaLabel1MouseEntered
        // TODO add your handling code here:
    }//GEN-LAST:event_ayudaLabel1MouseEntered

    private void exportarExcelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportarExcelButtonActionPerformed
        new ExcelJTableExporter(masterTable, "Feriados").export();
    }//GEN-LAST:event_exportarExcelButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.persistence.EntityManager SIAATPUEntityManager;
    private javax.swing.JLabel ayudaLabel1;
    private javax.swing.JButton borrarButton;
    private javax.swing.JButton cancelarButton;
    private javax.swing.JLabel descripcionLabel;
    private javax.swing.JTextArea descripcionTextArea;
    private javax.persistence.EntityManager entityManager;
    private javax.swing.JButton exportarExcelButton;
    private com.toedter.calendar.JDateChooser fechaFeriadoDateChooser;
    private javax.swing.JLabel fechaFeriadoLabel;
    private java.util.List<entities.Feriados> feriadosList;
    private javax.persistence.Query feriadosQuery;
    private javax.swing.JButton guardarButton;
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea jTextArea1;
    private java.util.List<entities.Feriados> list;
    private javax.swing.JScrollPane masterScrollPane;
    private javax.swing.JTable masterTable;
    private javax.swing.JButton nuevoButton;
    private javax.persistence.Query query;
    private javax.swing.JComboBox tipoFeriadoComboBox;
    private javax.swing.JLabel tipoFeriadoLabel;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    public static void main(Usuarios user) {
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AltaFeriados.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AltaFeriados.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AltaFeriados.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AltaFeriados.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        final Usuarios usuario = user;
        AltaFeriados.frame = new JFrame();
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                frame.setContentPane(new AltaFeriados(usuario));
                frame.setResizable(false);
                frame.pack();
                frame.setVisible(true);
                frame.setTitle("Organizacion   -   Feriados   -   SIAAT  ");
                frame.setIconImage(new ImageIcon(getClass().getResource("/images/logo.png")).getImage());
                frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                frame.addWindowListener(new WindowAdapter() {

                    public void windowClosing(WindowEvent e) {
                        if (frame != null) {
                            frame.setVisible(false);
                        }
                        frame = null;
                    }
                });
            }
        });
    }
}
